﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Security.Policy;
using HtmlAgilityPack;

namespace KindleComic
{
    public class MahuaCat : ComicSource
    {
        public MahuaCat() : base()
        {
            ComicSourceName = "漫画猫";
            ComicSourceUrl = "http://manhuacat.com";
            _client.BaseAddress = new Uri(ComicSourceUrl);
        }
        public override async Task<List<ComicInfo>> GetSearchListAsync(string key)
        {
            List<ComicInfo> ltComicInfo = new List<ComicInfo>();
            for (int i = 1; i < int.MaxValue; i++)
            {
                ltComicInfo.AddRange((await GetSearchListAsync(key, i).ConfigureAwait(false)).Item1);
            }

            return ltComicInfo;
        }
        public override async Task<List<ComicChapter>> GetComicChapterAsync(string url)
        {
            string htmlStr = await GetHtmlAsync(url).ConfigureAwait(false);
            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.LoadHtml(htmlStr);
            var nodeList = htmlDoc.DocumentNode.SelectNodes("//li[contains(@class,\"sort_div\")]");
            List<ComicChapter> ltConmicContents = new List<ComicChapter>();
            foreach (HtmlAgilityPack.HtmlNode node in nodeList)
            {
                string comicChapter = "", comicChapterUrl = "";

                comicChapter = node.SelectSingleNode("a").InnerText;

                comicChapterUrl = ((HtmlAgilityPack.HtmlNodeNavigator)node.CreateNavigator()).SelectSingleNode("a/@href")?.Value;

                ltConmicContents.Add(new ComicChapter()
                {
                    ChapterName = comicChapter,
                    ChapterUrl = comicChapterUrl
                });
            }
            return ltConmicContents;
        }

        public override async Task<Dictionary<int, string>> GetComicImagesAsync(string url)
        {
            string htmlStr = await GetHtmlAsync(url).ConfigureAwait(false);
            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.LoadHtml(htmlStr);

            var script = htmlDoc.DocumentNode.SelectSingleNode("/html/body/script[1]");
            string base64Str = script.InnerText.Replace("var img_data = '", "").Replace("';", "");
            var bytes = Convert.FromBase64String(base64Str);
            string json = System.Text.Encoding.UTF8.GetString(bytes);
            var ja = JArray.Parse(json);
            Dictionary<int, string> imgs = new Dictionary<int, string>();
            int i = 0;
            foreach (var j in ja)
            {
                var img = j["img"]?.ToString();
                if (!string.IsNullOrEmpty(img))
                {
                    int start = url.LastIndexOf("/");
                    int end = url.LastIndexOf(".");
                    var r = url.Substring(start, end - start);
                    img = "https://i2.manhuacat.com/ccbaike" + r.Replace("_", "/") + "/" + img;
                    i++;
                }
                imgs.Add(i, img);
            }
            return imgs;
        }

        public override async Task<Tuple<List<ComicInfo>, int>> GetSearchListAsync(string key, int page)
        {
            List<ComicInfo> ltComicInfo = new List<ComicInfo>();
            var url = string.Format("https://www.manhuacat.com/search.html?q={0}&page={1}", key, page);
            string htmlStr = await GetHtmlAsync(url).ConfigureAwait(false);
            if (string.IsNullOrEmpty(htmlStr))
            {
                return new Tuple<List<ComicInfo>, int>(ltComicInfo, 0);
            }
            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.LoadHtml(htmlStr);
            var nodeList = htmlDoc.DocumentNode.SelectNodes("//*[@class=\"comicbook-index mb-2 mb-sm-0\"]");
            if (nodeList == null)
            {
                return new Tuple<List<ComicInfo>, int>(ltComicInfo, 0);
            }

            foreach (HtmlAgilityPack.HtmlNode node in nodeList)
            {
                string comicName = "", comicUrl = "", comicCover = "", comicAuthor = "";
                ComicInfo comicInfo = new ComicInfo();

                comicName = node.SelectSingleNode("h2/a")?.InnerText;

                comicUrl = ((HtmlAgilityPack.HtmlNodeNavigator)node.CreateNavigator()).SelectSingleNode("a/@href")?.Value;

                comicCover = ((HtmlAgilityPack.HtmlNodeNavigator)node.CreateNavigator()).SelectSingleNode("a/img/@src")?.Value;

                foreach (HtmlNode n in node.SelectNodes("div[@class=\"one-line comic-author\"]/a"))
                {
                    comicAuthor += n.InnerText + " ";
                }

                comicInfo.ComicName = comicName;
                comicInfo.ComicUrl = comicUrl;
                if (comicCover.StartsWith("http"))
                {
                    comicInfo.CoverUrl = comicCover;
                }
                else
                {
                    comicInfo.CoverUrl = "https://www.manhuacat.com/" + comicCover;
                }
                comicInfo.ComicAuthor = comicAuthor;

                ltComicInfo.Add(comicInfo);
            }

            //最后一页标签
            var PageTags = htmlDoc.DocumentNode.SelectNodes("//a[contains(@href,'"+ url.Split('&')[0]+ "')]");
            if (PageTags != null)
            {
                //int countPage = Convert.ToInt32(PageTag.Attributes["href"].Value
                //    .Split(new string[] { "&p=" }, StringSplitOptions.RemoveEmptyEntries)
                //    [1]);
                var count = 0;
                foreach (var item in PageTags)
                {
                    int i = 0;
                    if (int.TryParse(item.InnerText,out i))
                    {
                        if (i>count)
                        {
                            count = i;
                        }
                    };
                }

                return new Tuple<List<ComicInfo>, int>(ltComicInfo, count);
            }
            else
            {
                return new Tuple<List<ComicInfo>, int>(ltComicInfo, 0);
            }
        }
    }
}
